// ==UserScript==
// @name         A【拉趣】自动申请脚本
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  自定义脚本，用于测试，拉取申请等
// @author       Timor
// @match        *://*.laqu.com/*
// @match        *://*.taobao.com/*

// @require      https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js

// @version      0.1
// @grant        unsafeWindow
// @grant        GM_openInTab
// @grant        GM_registerMenuCommand
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_getResourceText
// @grant        GM_info
// @grant        GM_setClipboard
// @connect      http://localhost:18081
// @run-at       document-end
// ==/UserScript==

//是否自动提交模式
window.laquAuto = 0;
//抓包服务地址
var serverUrl = 'http://localhost:18081';
//最大申请次数
var maxSqCount = 3; //最大申请次数
window.sySqCount = maxSqCount;//剩余申请次数 (初始值为max次)

//更改vue组件 - 申请倒计时弹窗
Vue.component("apply-popup",{props:{popFun:function(){},actionUrl:"",},data:function(){return{timer:"",btn:{time:1,text:"了解（5s）"}}},created:function(){this.countTime()},methods:{countTime:function(){var $this=this;if($this.timer){clearInterval($this.timer);return false}$this.timer=setInterval(function(){$this.btn.time-=1;if(!$this.btn.time){clearInterval($this.timer);$this.btn.text="了解";$this.btn.disable=false;return false}$this.btn.text="了解（"+$this.btn.time+"s）"},50)},goApply:function(){if(this.btn.time>0){return false}this.popFun()},closePop:function(){var $this=this;clearInterval($this.timer);this.btn.time=5;this.$parent.isShow=false}},template:'<div class="container">'+'<div class="copy apply_box">'+'<i class="iconfont iconguanbi" @click="closePop"></i>'+'<div class="header">申请注意事项</div>'+'<div class="apply_content">'+"<p>违反规则 , 不予提现 , 封号处理</p>"+"1、不许旺旺联系商家提 : 拉趣 / 试用字样</br>"+"2、不允许使用淘宝返利</br>"+"3、不允许私自使用优惠劵</br>"+"4、私自退款，乱传图片"+"</div>"+'<button class="btn" :class="{disabled:btn.time!=0}" @click="goApply">{{btn.text}}</button>'+"</div>"+"</div>"});

//初始化
$(function () {
    InitLaQuPage()
})

//初始化页面
var InitLaQuPage = function () {

    //初始化申请条件
    function initShenqingParam(config) {
        config = config || {}
        window.goodsSize = 50; //商品数量
        window.ignore = config.ignore || {}; //请求忽略值
        window.sySqCount = config.sySqCount || window.sySqCount; //剩余申请次数
        $('.change_keyword').trigger('click'); //重置关键词
    }

    //获取商品列表
    function getGoodsList(html) {
        var goods = [];
        var items = $(html).find('.m-itemlist .items .item');
        for (let i = 0; i < items.length; i++) {
            var $item = $(items[i]);
            var itemData = {
                price: $item.find('.price').text().trim(),
                name: $item.find('.title').text().trim(),
                shopname: $item.find('.shop').text().trim(),
                detailUrl: 'https:' + $item.find('.title .J_ClickStat').attr('href')
            }
            goods.push(itemData);
        }
        return goods;
    }

    //检测商品是否正确
    function checkRightGoods(items, shopReg) {
        console.log('检测商品数量：' + items.length);
        var reg = new RegExp(shopReg, 'gi');
        var goods = [];
        for (let item of items) {
            if (reg.test(item.shopname)) {  //匹配成功
                goods.push(item);
                console.log('商品列表匹配成功：' + JSON.stringify(item));
            }
        }
        return goods;
    }

    //设置页面参数
    function setLaquPageGoodsData(good) {

        $("#auth_code1").val(good.detailUrl)

        //设置 确认【宝贝|店铺】收藏
        $('.check_collect1,.check_collect2').prop('checked', true);
        $('.collectstuis').hide()
        //去除按钮禁用
        $('#apply_for_link').attr('disabled', false).css({'background': 'rgb(255, 54, 111)'})
        //缓存商品数据 (三天自动失效)
        CommonUtil.setCookie(new Date().toLocaleDateString() + "__" + good.name, JSON.stringify(good), 3 * 24 * 60)
        //是否自动提交
        window.laquAuto && document.getElementById('apply_for_link').click();

        //数据清空,退出循环
        window.sySqCount = 0;
    }

    //申请环节
    function shenqing(config) {
        config = config || {};

        //验证剩余申请次数
        if (window.sySqCount <= 0) return;

        //次数增加
        window.goodsSize += config.size || 0;
        window.sySqCount -= 1;
        //忽略变更
        config.ignore && Object.assign(window.ignore, config.ignore);

        var key = $('.item_title .theme').text();
        var price = $(".detail_item .item_box:contains(商品价格) i").text().replace(/￥/g,'').replace(/[^0-9(.)?]/ig, "");
        //替换所有*为正则验证
        var bossWangwang = $(".detail_item .item_box:contains(掌柜旺旺) i").text().replace('\*', "?+?").replace(/\*/g, '').replace('?+?', "(\\s|\\S|\\w|\\W)*");
        //淘宝参数
        var taobaoParam = {
            'q': key,
            'size': window.goodsSize,
        }   //encodeURI 和 decodeURI
        //是否忽略价格
        if (window.ignore.price != false) {
            taobaoParam['filter'] = `reserve_price[${price},${price}]`;
        }
        //请求参数
        var reqData = {
            'tb_enc': GM_getValue('tb_enc'),       //淘宝使用
            'tb_x5sec': GM_getValue('tb_x5sec'),   //淘宝使用
            'url': 'https://s.taobao.com/search?' + $.param(taobaoParam)
        }

        //获取淘宝数据
        $.ajax({
            url: serverUrl + "/getTaobaoGoods.json",    //请求的url地址
            data: reqData,
            type: "POST",   //请求方式
            success: function (req) {
                handleShenqing(req,bossWangwang);
            },
            error: function (err) {
                console.log(err)
                window.sySqCount = 0;
                alert('网络响应错误，请检查淘宝服务是否正常启动！')
            }
        });
    }
    //处理申请响应
    async function handleShenqing(req,bossWangwang){
        //请求成功时处理
        if (req.code != 0) {  //不成功
            alert(req.message)
            var taobaoWin = window.open(req.url)
            setTimeout(() => { //两秒后检测窗口已经跳转,自动关闭此窗口
                if (taobaoWin.window.location.href.includes('laqu')) {
                    window.close();
                }
            }, 2000)
            //三秒后检测code是否获取成功，关闭页面
        } else {  //成功
            //得到所有商品
            var allItems = getGoodsList(req.html);
            console.log('剩余次数:' + window.sySqCount + '，商品数量：' + allItems.length)
            if (!window.noMatchFlag &&                      //匹配不到商品标识
                (!allItems.length || window.sySqCount == 0)) {  //商品不存在，或最后一次申请时

                if (confirm("未找到响应商品，是否模糊匹配？")) {
                    window.noMatchFlag = true;
                    initShenqingParam({sySqCount: 1});
                    shenqing({ignore: {price: false}})
                } else {

                    //设置 确认【宝贝|店铺】收藏
                    $('.check_collect1,.check_collect2').prop('checked', true);
                    $('.collectstuis').hide()
                    //去除按钮禁用
                    $('#apply_for_link').attr('disabled', false).css({'background': 'rgb(255, 54, 111)'})

                    window.open(reqData.url)
                }
            } else { //商品存在
                //得到匹配的商品
                var goods = checkRightGoods(allItems, bossWangwang);
                if (goods && goods.length) {//存在匹配数据
                    for (let i in goods) {
                        let good = goods[i];
                        //设置链接
                        $('.validate input[type="text"]').trigger('focus');
                        $('.validate input[type="text"]').val(good.detailUrl);
                        await CommonUtil.sleep(1000)
                        $('.validate input[type="text"]').trigger('blur');
                        await CommonUtil.sleep(1000)
                        $('.check_btn').trigger('click')
                        await CommonUtil.sleep(500000)
                        //不存在错误消息 或 最后一个匹配的
                        if (!$('.validate input[type="text"]').next('.error_info').text() || i == goods.length - 1) {
                            setLaquPageGoodsData(good);
                            break;
                        }
                    }
                } else {   //查询其他页数据是否匹配
                    if (window.sySqCount > 0) {
                        shenqing() //重新申请
                    } else if (window.sySqCount == 0) {    //最后一次，设置模糊商品
                        let good = allItems[0];
                        setLaquPageGoodsData(good);
                    }
                }
            }
        }
    }

    let url = location.href;
    if (url.includes('laqu.com')) {
        //拉趣页面
        //申请界面
        if (url.includes('laqu.com/activity') ||
            url.includes('item/get')) {
            if ($('.box-btn.active').length) {   //第一次申请
                //按钮点击
                $('.box-btn.active').trigger('click');
                //忽略弹出框的5秒等待
                setTimeout(() => {
                    window.laquAuto && $('.apply_box .btn').trigger('click');
                }, 500)
            } else {  //继续任务
                //按钮点击
                window.laquAuto && $('#award_btns').trigger('click');
            }
        } else if (url.includes('www.laqu.com/user/activity/apply-v2.html') ||          //领取界面
            url.includes('laqu.com/user/myapply/continueTask')) {   //待提交-继续任务
            initShenqingParam();//初始化参数
            setTimeout(shenqing, 1000);//x秒后调用申请
        }
    } else if (url.includes('taobao.com')) { //淘宝
        // enc为httpOnly，js已无法获取
        GM_setValue('tb_enc', CommonUtil.readCookie('tb_enc'));

        let x5sec = CommonUtil.readCookie('x5sec');
        if (x5sec && x5sec != GM_getValue('tb_x5sec')) {
            GM_setValue('tb_x5sec', x5sec);
            //由拉趣打开的页面
            if (window.opener && window.opener.window.location.href.includes('laqu')) {
                alert('拉趣tb_x5sec已更新：' + GM_getValue('tb_x5sec'))
                setTimeout(() => {
                    window.opener.window.location.reload(); //父窗口刷新
                    window.close()
                }, 1000)
            }
        }

    }
}


//工具类
class CommonUtil {
    constructor() {
    }

    //等待
    static sleep = (ms)=>{
        return new Promise(resolve => setTimeout(resolve, ms))
    }

    //cookie工具类
    /***
     *读取指定的Cookie值 readCookie("id");
     *@param {string} cookieName Cookie名称
     */
    static readCookie = (cookieName) => {
        var theCookie = "" + document.cookie;
        var ind = theCookie.indexOf(cookieName);
        if (ind == -1 || cookieName == "") return "";
        var ind1 = theCookie.indexOf(';', ind);
        if (ind1 == -1) ind1 = theCookie.length;
        /*读取Cookie值*/
        return unescape(theCookie.substring(ind + cookieName.length + 1, ind1));
    };
    /***
     * 设置Cookie值 setCookie("id",1);
     * @param {string} cookieName Cookie名称
     * @param {string} cookieValue Cookie值
     * @param {number} time Cookie过期时间 （分钟）
     */
    static setCookie = (cookieName, cookieValue, expireTime) => {
        var cookieText = cookieName + "=" + escape(cookieValue);
        /*计算Cookie过期时间【 3600000 * 24  为一天】*/
        if (expireTime) {
            var today = new Date();
            var expire = new Date();
            expire.setTime(today.getTime() + expireTime * 60 * 1000);
            cookieText = cookieText + ";expires=" + expire.toGMTString();
        }
        document.cookie = cookieText;
    }

    /***
     * 删除cookie中指定变量函数
     * @param {string} $name Cookie名称
     */
    static deleteCookie = ($name) => {
        var myDate = new Date();
        myDate.setTime(-1000);//设置时间
        document.cookie = $name + "=''; expires=" + myDate.toGMTString();
    }

    /***
     * 删除cookie中所有定变量函数
     */
    static clearCookie = () => {
        var myDate = new Date();
        myDate.setTime(-1000);//设置时间
        var data = document.cookie;
        var dataArray = data.split("; ");

        for (var i = 0; i < dataArray.length; i++) {
            var varName = dataArray[i].split("=");
            document.cookie = varName[0] + "=''; expires=" + myDate.toGMTString();
        }
    }

    //随机数
    static getRandom = () => {
        var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
        var nums = "";
        for (var i = 0; i < 32; i++) {
            var id = parseInt(Math.random() * 61);
            nums += chars[id];
        }
        return nums;
    }

}
